<template>
  <el-button @click="handleClick" :disabled="isCounting || loading" :loading="loading">
    {{ isCounting ? countdown + 's' : text }}
  </el-button>
</template>

<script setup>
import { ref, onBeforeUnmount, defineProps } from "vue";

// 定义组件的 props
const props = defineProps({
  loading: {
    type: Boolean,
    default: false,
  },
  text: {
    type: String,
    default: "点击倒计时",
  },
  countdownTime: {
    type: Number,
    default: 60, // 默认倒计时10秒
  },
});
const emit = defineEmits(["on-click"]);
const handleClick = () => {
    emit('on-click')
}
// 定义响应式状态
const countdown = ref(props.countdownTime);
const isCounting = ref(false);
let timer = null;

// 开始倒计时的函数
const startCountdown = () => {
  if (isCounting.value) return; // 防止重复点击
  isCounting.value = true;
  countdown.value = props.countdownTime;

  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
      isCounting.value = false;
    }
  }, 1000);
};

// 组件销毁前清理定时器
onBeforeUnmount(() => {
  clearInterval(timer);
});

// 暴露给外部的方法
defineExpose({
  startCountdown
});
</script>
